package com.seasun.xg.lamp.logserver;

import javax.transaction.Transactional;

import org.academy.funfair.FunfairProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.seasun.xg.lamp.repo.LogVo;

@Service
public class LogServerService {
	@Autowired
	private LogServerRepository repo;
	@Autowired
	private LogSeqRepository seqRepo;

	private long lastMillis = 0;
	private long lastSeq = 0;

	@Transactional
	public String newSeq(String remoteIp, String serverIp, int serverPort) {
		final long millisecond = System.currentTimeMillis();

		if (lastMillis == millisecond) {
			++lastSeq;
		} else {
			lastMillis = millisecond;
			lastSeq = 0;
		}

		final String seq = String.valueOf(millisecond * 100_000 + lastSeq);
		final LogVo vo = new LogVo();
		final LogSeqVo seqVo = new LogSeqVo();

		seqVo.seq = seq;

		seqRepo.save(seqVo);

		vo.seq = seq;
		vo.source = "lamp";
		vo.serverIp = serverIp;
		vo.serverPort = serverPort;
		vo.publicIp = remoteIp;
		vo.appName = FunfairProperties.getName();
		vo.appVersion = FunfairProperties.getVersion();
		vo.level = "INFO";
		vo.content = String.format("Create sequence %s.", seq);
		vo.bodyTimestamp = System.currentTimeMillis();

		repo.save(vo);

		return seq;
	}

	public void pushDeviceLog(LogVo vo) {
		repo.save(vo);
	}

	public void pushServerLog(LogVo vo) {
		repo.save(vo);
	}
}
